package com.thread;

import java.util.LinkedList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class JUC_taotao_interview2_lock_25 {
    static private int MAX = 10;
    final private LinkedList<Object> list = new LinkedList<>();
    private int count = 0;
    private Lock lock = new ReentrantLock();
    private Condition consumber = lock.newCondition();
    private Condition produser = lock.newCondition();
    //生产者
    private  void put(Object obj){
        try {
            lock.lock();
            while (list.size() == MAX){//为什么不用if?
                try {
                    produser.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            ++count;
            list.add(new Object());
            System.out.println(Thread.currentThread().getName() + " product ... ");
            consumber.signalAll();
        } finally {
            lock.unlock();
        }

    }
    //消费者
    private  Object get(){
        try {
            lock.lock();
            while(list.size() == 0){
                try {
                    consumber.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
            --count;
            Object obj = list.removeFirst();
            System.out.println(Thread.currentThread().getName() + " revome consumer ... ");

            produser.signalAll();
            return obj;
        } finally {
            lock.unlock();
        }

    }

    public static void main(String[] args) {
        JUC_taotao_interview2_lock_25 t = new JUC_taotao_interview2_lock_25();
        for(int i=0;i<2;i++){
            new Thread(()->{
                for(int j=0;j<100;++j){
                    t.put(Thread.currentThread().getName()+"put");
                }

            },"p"+i).start();
        }
        for(int i=0;i<10;i++){
            new Thread(()->{
                t.get();
            },"c"+i).start();
        }
    }
}
